package com.rds.eco.service.impl;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.rds.common.ServiceException;
import com.rds.common.api.eco.IRdaEcoApi;
import com.rds.common.api.eco.domain.RdaEco;
import com.rds.common.api.eco.domain.RdaEcoRel;
//import com.rds.common.api.workflow.IRdaWorkflowApi;
import com.rds.common.api.material.domain.MaterialBill;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;

import com.rds.eco.mapper.RdaEcoMapper;
import com.rds.eco.service.IRdaEcoRelService;
import com.rds.eco.service.IRdaEcoService;
import com.rds.material.mapper.MaterialBillMapper;
import com.rds.material.service.IMaterialBillService;
import com.rds.material.service.IRdaPartService;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.material.utils.WorkspaceUtils;
//import com.rds.system.domain.RdaFolderRel;
import com.rds.system.domain.Sharing;
import com.rds.system.service.*;
//import com.rds.workflow.service.RdaWorkflowTempleteScopeService;
//import com.rds.workspace.service.IRdaCadfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-12-07
 */
@Service
public class RdaEcoServiceImpl implements IRdaEcoService, IRdaEcoApi
{
    @Autowired
    private IRdaTypeService rdaTypeService;

//    @Autowired
//    private IRdaFolderRelService rdaFolderRelService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

//    @Autowired
//    private IDocumentService documentService;

//    @Autowired
//    private RdaWorkflowTempleteScopeService rdaWorkflowTempleteScopeService;

//    @Autowired
//    private IRdaWorkflowApi rdaWorkflowTempleteScopeService;

    @Autowired
    private RdaEcoMapper rdaEcoMapper;

    @Autowired
    private IRdaStateService rdaStateService;


    @Autowired
    private ISysHistoryService sysHistoryService;

    @Autowired
    private IRdaNameCodeService rdaNameCodeService;

//    @Autowired
//    private IRdaCadfileService rdaCadfileService;

    @Autowired
    private IMaterialBillService materialBillService;

    @Autowired
    private MaterialBillMapper materialBillMapper;

    @Autowired
    private IRdaEcoRelService rdaEcoRelService;

    @Autowired
    private IRdaPartService rdaPartService;



    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public RdaEco selectRdaEcoById(Long id)
    {
        return rdaEcoMapper.selectRdaEcoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param rdaEco 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<RdaEco> selectRdaEcoList(RdaEco rdaEco)
    {
        return rdaEcoMapper.selectRdaEcoList(rdaEco);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param rdaEco 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertRdaEco(RdaEco rdaEco)
    {
        //自动编码
        if (rdaEco.getName() == null) {
            rdaEco.setName(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(rdaEco.getTypeid()),""));
        }
        rdaEco.setCreateTime(DateUtils.getNowDate());
        rdaEco.setId(SnowFlakeUtils.nextId());
        rdaEco.setOwnerid(SecurityUtils.getUserId());
        //添加流程
//        rdaWorkflowTempleteScopeService.createWorkflowWithObject(rdaEco.getTypeid().longValue(),rdaEco.getPolicyid().longValue(),rdaEco.getStateid().longValue(),rdaEco.getId(),"eco",rdaEco.getName());
//        new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(rdaEco.getId(),"创建",rdaEco.getStateid(),"eco管理模块","");
        return rdaEcoMapper.insertRdaEco(rdaEco);
    }

    /**
     * 修改【请填写功能名称】
     * @param rdaEco 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateRdaEco(RdaEco rdaEco)
    {
        return rdaEcoMapper.updateRdaEco(rdaEco);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRdaEcoByIds(Long[] ids)
    {
        return rdaEcoMapper.deleteRdaEcoByIds(ids);
    }

    @Override
    public int removeRelById(Long[] ids) {
        return rdaEcoRelService.deleteRdaEcoRelByIds(ids);
    }

    @Override
    public JSONObject toMaterial(Long id) {
//        RdaEcoRel rdaEcoRel = rdaEcoRelService.selectRdaEcoRelById(id);
//        rdaEcoRel.
//        return rdaPartService.getInfo();
        return null;
    }


    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRdaEcoById(Long id)
    {
        return rdaEcoMapper.deleteRdaEcoById(id);
    }

    @Override
    public int addFile(Sharing rdaMemberlistUser) {
//        Long dId = rdaMemberlistUser.getProjectid();
//        List<RdaCadfile> fileList=rdaMemberlistUser.getFileList();
//        if(fileList==null){
//            throw new ServiceException("请选择需要上传的文件");
//        }
//        RdaCadfile rdaCadfile=new RdaCadfile();
//        rdaCadfile.setObjectid(dId);
//        rdaCadfile.setStatus(1L);
//        List<RdaCadfile> listFile=rdaCadfileService.selectRdaCadfileList(rdaCadfile);
//        int count=0;
//        int count1=0;
//        if(listFile.size()!=0){
//            count=Integer.parseInt(listFile.get(listFile.size()-1).getRevision());//获取当前最大版本号
//        }
//        int rows = 0;
//        String username = SecurityUtils.getUsername();
//        for(RdaCadfile file:fileList){
//            String suffix= WorkspaceUtils.getFileSuffix(file.getFileName(),"2");
//            count++;
//            rdaCadfile.setFileName(file.getFileName());
//            int num=rdaCadfileService.selectRdaCadfileList(rdaCadfile).size();
//            if(num>0){
//                count1++;
//            }else{
//                file.setMasterid(SnowFlakeUtils.nextId());
//                file.setId(SnowFlakeUtils.nextId());
//                file.setObjectid(dId);
//                file.setFileSize(""+Integer.parseInt(file.getFileSize()));
//                file.setUserName(username);
//                file.setCreateTime(DateUtils.getNowDate());
//                file.setFormat(suffix);
//                rows=rdaCadfileService.insertRdaCadfile(file);
//                //通过eco关系表找到materialbill
//                RdaEco rdaEco = rdaEcoMapper.selectRdaEcoById(dId);
////                new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(dId,"添加附件",rdaEco.getStateid(),"物料零件",file.getFileName());
//            }
//        }
//        if(count1>0){
//            if(rows>0){
//                throw new ServiceException("操作成功，"+count1+"个文件已存在，请用更新文件操作！");
//            }else{
//                throw new ServiceException(("操作失败，已存在同文件名文件"));
//            }
//        }
//        return rows;
        return 0;
    }

    @Override
    public void InsertExistMaterial(Sharing rdaPmsassignRel) {
        String ids = rdaPmsassignRel.getIds();
        String[] split = ids.split(",");
        List<Long> lid = (List<Long>) CollectionUtils.arrayToList(split);
        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillByIds(lid);
        Long projectid = rdaPmsassignRel.getProjectid();
        RdaEco rdaEco = rdaEcoMapper.selectRdaEcoById(projectid);
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> Stateid=(Map<String,Long>)dmap.get("Stateid");
        Long fq = Stateid.get("Obsolete");
        Long fb = Stateid.get("Release");
        for (MaterialBill materialBill : materialBillList) {
            //判断是否废弃
            if (fq.toString().equals(materialBill.getStateid().toString())){
                throw new ServiceException("物料状态为废弃状态："+materialBill.getName());
            }
            //判斷是否重複
            RdaEcoRel rdaEcoRel = new RdaEcoRel();
            rdaEcoRel.setFromid(materialBill.getId());
            rdaEcoRel.setToid(projectid);
            List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRdaEcoRelList(rdaEcoRel);
            if (!CollectionUtils.isEmpty(rdaEcoRels)){
                throw new ServiceException("存在相同物料："+materialBill.getName());
            }
            rdaEcoRel.setId(SnowFlakeUtils.nextId());
            rdaEcoRel.setName(materialBill.getName());
            rdaEcoRel.setVersion(materialBill.getRevision());
            rdaEcoRel.setStateid(Long.parseLong(materialBill.getStateid().toString()));
            rdaEcoRel.setDescription(materialBill.getDescription());
            rdaEcoRel.setOwnerid(SecurityUtils.getUserId());
            rdaEcoRel.setFromid(materialBill.getId());
            rdaEcoRel.setFromtype(Long.parseLong(materialBill.getTypeid().toString()));
            rdaEcoRel.setToid(projectid);
            rdaEcoRel.setTotype(rdaEco.getId());
            rdaEcoRel.setSeries(materialBill.getParentid());
            rdaEcoRel.setCreateTime(DateUtils.getNowDate());
            rdaEcoRel.setTypeid(rdaEcoRel.getFromtype());
            if (materialBill.getStateid().toString().equals(fb.toString())){
                rdaEcoRel.setRequestChange("更改");
            }else {
                rdaEcoRel.setRequestChange("发布");
            }
            rdaEcoRelService.insertRdaEcoRel(rdaEcoRel);
        }
    }

    @Override
    public void InsertMaterial(MaterialBill materialBill) {
        RdaEco rdaEco = rdaEcoMapper.selectRdaEcoById(materialBill.getProjectid());
        materialBill.setId(SnowFlakeUtils.nextId());
        //自动编码
        if (materialBill.getCode() == null) {
            if (materialBill.getNametype()!=null){
                materialBill.setCode(materialBill.getNametype().concat(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()), "")));
            }else {
                materialBill.setCode(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()),""));
            }
        }
        //添加版本规则
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        String revision=dmap.get("revision").toString();
        materialBill.setRevision(revision);
        //判断是否有相同物料
        MaterialBill materialBillC = new MaterialBill();
        materialBillC.setName(materialBill.getName());
        materialBillC.setCode(materialBill.getCode());
        materialBillC.setRevision(materialBill.getRevision());
        List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillList(materialBillC);
        if (materialBillList.size()>0){
            throw new ServiceException("有相同物料");
        }
        materialBillMapper.insertMaterialBill(materialBill);
        RdaEcoRel rdaEcoRel = new RdaEcoRel();
        rdaEcoRel.setId(SnowFlakeUtils.nextId());
        rdaEcoRel.setName(materialBill.getName());
        rdaEcoRel.setVersion(materialBill.getRevision());
        rdaEcoRel.setStateid(Long.parseLong(materialBill.getStateid().toString()));
        rdaEcoRel.setDescription(materialBill.getDescription());
        rdaEcoRel.setOwnerid(SecurityUtils.getUserId());
        rdaEcoRel.setFromid(materialBill.getId());
        rdaEcoRel.setFromtype(Long.parseLong(materialBill.getTypeid().toString()));
        rdaEcoRel.setToid(materialBill.getProjectid());
        rdaEcoRel.setTotype(rdaEco.getId());
        rdaEcoRel.setCreateTime(DateUtils.getNowDate());
        rdaEcoRel.setTypeid(rdaEcoRel.getFromtype());
        rdaEcoRel.setSeries(materialBill.getParentid());
        rdaEcoRel.setRequestChange("发布");
        rdaEcoRelService.insertRdaEcoRel(rdaEcoRel);
        //生命周期
//        rdaWorkflowTempleteScopeService.createWorkflowWithObject(materialBill.getTypeid().longValue(),materialBill.getPolicyid().longValue(),materialBill.getStateid().longValue(),SnowFlakeUtils.nextId(),"part",materialBill.getName());
        //历史记录
//        new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(materialBill.getId(),"创建",materialBill.getStateid(),"物料零件","");
    }

    @Override
    public void InsertExistDoc(Sharing rdaPmsassignRel) {
//        String ids = rdaPmsassignRel.getIds();
//        String[] split = ids.split(",");
//        Long projectid = rdaPmsassignRel.getProjectid();
//        RdaEco rdaEco = rdaEcoMapper.selectRdaEcoById(projectid);
//        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("Document","1",rdaTypeService,rdaPolicyService,rdaStateService);
//        Map<String,Long> Stateid=(Map<String,Long>)dmap.get("Stateid");
//        Long fq = Stateid.get("Obsoleted");
//        Long fb = Stateid.get("Release");
//        for (String s : split) {
//            Document document = documentService.selectDocumentById(Long.parseLong(s));
//            //判断是否废弃
//            if (fq.toString().equals(document.getStateid().toString())){
//                throw new ServiceException("物料状态为废弃状态："+document.getName());
//            }
//            //判斷是否重複
//            RdaEcoRel rdaEcoRel = new RdaEcoRel();
//            rdaEcoRel.setFromid(document.getId());
//            rdaEcoRel.setToid(projectid);
//            List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRdaEcoRelList(rdaEcoRel);
//            if (!CollectionUtils.isEmpty(rdaEcoRels)){
//                throw new ServiceException("存在相同文档："+document.getName());
//            }
//            rdaEcoRel.setId(SnowFlakeUtils.nextId());
//            rdaEcoRel.setName(document.getName());
//            rdaEcoRel.setVersion(document.getRevision());
//            rdaEcoRel.setStateid(Long.parseLong(document.getStateid().toString()));
//            rdaEcoRel.setDescription(document.getDescription());
//            rdaEcoRel.setOwnerid(SecurityUtils.getUserId());
//            rdaEcoRel.setFromid(document.getId());
//            rdaEcoRel.setFromtype(Long.parseLong(document.getTypeid().toString()));
//            rdaEcoRel.setToid(projectid);
//            rdaEcoRel.setTotype(rdaEco.getId());
//            rdaEcoRel.setCreateTime(DateUtils.getNowDate());
//            rdaEcoRel.setTypeid(rdaEcoRel.getFromtype());
//            if (document.getStateid().toString().equals(fb.toString())){
//                rdaEcoRel.setRequestChange("更改");
//            }else {
//                rdaEcoRel.setRequestChange("发布");
//            }
//            rdaEcoRelService.insertRdaEcoRel(rdaEcoRel);
//        }
        return;
    }

    @Override
    public AjaxResult InsertDoc(Document document) {
//        if(SecurityUtils.verifyPermissions("created", String.valueOf(document.getStateid()))){
//            throw new ServiceException("您没有此状态的创建权限！");
//        }
//        List<Document> checkUniqueDocument = documentService.checkDocumentUnique(document);
//        if(checkUniqueDocument.size() == 0){
//            String username = SecurityUtils.getUsername();
//            document.setUsername(username);
//            Long userId = SecurityUtils.getUserId();
//            document.setOwnerid(userId);
//            document.setCompanyId(SecurityUtils.getCompanyId());
//            document.setId(SnowFlakeUtils.nextId());
//            /*创建时 首版本字段设置为true 2021-12-15**/
//            document.setFirstVersion(true);
//
//            long dId = document.getId();
//            int rows = documentService.insertDocument(document);
//
//            /*创建文档时记录历史记录 2021-12-13*/
////            new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(dId,"创建",document.getStateid(),"文档管理","");
//            if(rows>0){
//                Long FolderId = document.getParentid();
//                if(FolderId != null && FolderId > 0){
//                    RdaFolderRel folderRel=new RdaFolderRel();
//                    folderRel.setId(SnowFlakeUtils.nextId());
//                    folderRel.setFolderId(FolderId);
//                    folderRel.setProjectId(document.getProjectid());
//                    folderRel.setDocId(dId);
//                    rdaFolderRelService.insertRdaFolderRel(folderRel);
//                    /*连接文档夹时记录历史记录 2021-12-13*/
////                    new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(dId,"连接",document.getStateid(),"文档管理","");
//                }
//
//                /*修改逻辑:创建页面附件不一定要上传 不上传时为空 2021-12-15****/
//                List<File> fileList= document.getFileList();
//                //System.out.println("fileList = " + fileList);
//                if(fileList !=null && !fileList.isEmpty()){
//                    //int count=0;
//                    for(File file:fileList){
//                        //count++;
//                        file.setId(SnowFlakeUtils.nextId());
//                        file.setDocId(dId);
//                        file.setFileSize(""+Integer.parseInt(file.getFileSize())/1024);
//                        file.setUserName(username);
//                        file.setFileId(SnowFlakeUtils.nextId());
//                        file.setCreateTime(DateUtils.getNowDate());
//                        /*file.setRevision(""+count);*/
//                        //fileName.add(file.getFileName());
//                        documentService.insertFile(file);
//
//                        /*连接文档夹时记录历史记录 2021-12-13*/
////                        new HistoryRecordUtil(rdaStateService,sysHistoryService).recordHistory(dId,"添加附件",document.getStateid(),"文档管理",file.getFileName());
//                    }
//                }
//            }
//            //绑定当前eco
//            RdaEco rdaEco = rdaEcoMapper.selectRdaEcoById(document.getProjectid());
//            RdaEcoRel rdaEcoRel = new RdaEcoRel();
//            rdaEcoRel.setId(SnowFlakeUtils.nextId());
//            rdaEcoRel.setName(document.getName());
//            rdaEcoRel.setVersion(document.getRevision());
//            rdaEcoRel.setStateid(Long.parseLong(document.getStateid().toString()));
//            rdaEcoRel.setDescription(document.getDescription());
//            rdaEcoRel.setOwnerid(SecurityUtils.getUserId());
//            rdaEcoRel.setFromid(document.getId());
//            rdaEcoRel.setFromtype(Long.parseLong(document.getTypeid().toString()));
//            rdaEcoRel.setToid(document.getProjectid());
//            rdaEcoRel.setTotype(rdaEco.getId());
//            rdaEcoRel.setCreateTime(DateUtils.getNowDate());
//            rdaEcoRel.setTypeid(rdaEcoRel.getFromtype());
//            rdaEcoRel.setRequestChange("发布");
//            rdaEcoRelService.insertRdaEcoRel(rdaEcoRel);
//
//            return rdaWorkflowTempleteScopeService.createWorkflowWithObject(document.getTypeid(),document.getPolicyid(),document.getStateid().longValue(),document.getId(),"document",document.getName());
////            return toAjax(rows);
//        }else{
//            throw new ServiceException("当前对象系统已存在! 名称:"+document.getName()+",版本:"+document.getRevision());
//        }
    return null;

    }

//    @Override
//    public List<RdaEcoRel> selectRelsByEcoId(Long id) {
//        RdaEcoRel rdaEcoRel = new RdaEcoRel();
//        rdaEcoRel.setToid(id);
//        List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRdaEcoRelList(rdaEcoRel);
//        return rdaEcoRels;
//    }
    @Override
    public List<RdaEcoRel> selectRelsByEcoId(Long id) {
        List<RdaEcoRel> rdaEcoRels = rdaEcoRelService.selectRelsByEcoId(id);
        return rdaEcoRels;
    }


}
